package com.jdz.gxq.info.admin.file.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.jdz.gxq.info.admin.file.bo.FileInfo;
import com.jdz.gxq.info.admin.file.bo.ImageInfo;
import com.jdz.gxq.info.admin.file.form.UploadForm;
import com.jdz.gxq.info.admin.file.service.FileService;
import com.jdz.gxq.info.common.action.CommonAction;
import com.jdz.gxq.info.common.constant.Constant;
import com.jdz.gxq.info.common.utils.FileUtils;

public class UploadAction extends CommonAction {

	private FileService fileService = null;
	 
	public ActionForward doExecute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws java.lang.Exception {
		
		UploadForm uploadForm = (UploadForm) form;

		// 文件上传相对路径
		String relativePath = Constant.IMAGE_PATH_ESTATE;
		
		FormFile file = uploadForm.getFile();

		HttpSession session = request.getSession();
		
		// 取得文件上传的物理路径
		String realPath = session.getServletContext().getRealPath(relativePath);
		
		// 上传文件
		FileInfo fileInfo = FileUtils.uploadFile(realPath, file);
		fileInfo.setRelativePath(relativePath);
		
		// 讲文件信息保存到数据库中
		ImageInfo imageInfo = new ImageInfo();
		imageInfo.setPictureId(fileInfo.getFileid());
		imageInfo.setPictureName(fileInfo.getFileName());
		imageInfo.setPictureUrl(relativePath);
		imageInfo.setModifiedBy(getUserId(request));
		fileService.insertImageInfo(imageInfo);
		
		// 将上传后的文件信息返回画面
		response.getWriter().print(JSONArray.fromObject(fileInfo).toString());
		
		return null;
	}
	
	public void setFileService(FileService fileService) {
		this.fileService = fileService;
	}
}

